////<!--车主信息-->
import api from '../../../fetch/api'

export default {
  data() {
    return {
      importResult: '',
      importFile:{
          importFile:'',

      },
      importRules:{

      },

    }
  },
  computed: {
    showAddIcon() {
      return this.carCodeListStr.length - 1;
    }
  },
  created() {
    this.toBase(this);
    
  },
  methods: {
    getList() {
      this.getTraderList(this.searchParams);
    },
    //图片转bas64
    toBase(vm) {
      console.log("执行了  this.toBase(this)")
      $(document).on('change', "#traderpic", function () {
        console.log("执行了  this.toBase(this)》》》》.change")
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          vm.showToast('请确保文件为图像类型', 2, 2000);
          $("#traderpic").val('');
          return false;
        }
        vm.traderModalData.identityCardImg = file.name;
        console.log(file.name);
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          console.log(e);
          var res = e.target.result.replace("data:image/png;base64,", "");
          res = res.replace("data:image/jpg;base64,", "");
          res = res.replace("data:image/jpeg;base64,", "");
          //vm.traderpic = res;
          vm.traderModalData.identityCardImgPic = res;
          console.log('vm.traderModalData.pic_base64', vm.traderpic)
        };
      });

      $(document).on('change', "#carpic", function () {
        console.log("执行了  this.toBase(this)》》》》.change")
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          vm.showToast('请确保文件为图像类型', 2, 2000);
          $("#carpic").val('');
          return false;
        }
        //将图片名称保存在临时记录中
        vm.tempPic.drivingLicensePicture = file.name;
        console.log(file.name);
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          console.log(e);
          var res = e.target.result.replace("data:image/png;base64,", "");
          res = res.replace("data:image/jpg;base64,", "");
          res = res.replace("data:image/jpeg;base64,", "");
          vm.carpic = res;
          vm.tempPic.drivingLicensePic=res;
          console.log('vm.traderModalData.pic_base64', vm.carpic)
        };
      });


    },

    traderModal_edit(data) {
      var _this = this;
      console.log('traderModal_edit>>data', data)
      var sourceData = data;
      var editdata = {
        url: "/parkVip/parkCustomer/detail.do",
        id: '',
        customerName: '',
        customerSex: '',
        customerTelphone: '',
        defaultCarLicense: '',
        customerCompany: '',
        customerDepartment: '',
        customerAddress: '',
        customerRoomNumber: '',
        identityCardNumber: '',
        identityCardImgPic: '',
        identityCardImg: '',
        remark1: '',
        remark2: '',
        remark3: '',
        carConfigList1: [],
      };

      var params = {};
      params.parkCustomerId = data.id;

      API.park.parkCustomerDetail(params).then(res => {
        //start
        var data = res;
        editdata.id = data.data.id;
        editdata.customerName = data.data.customerName;
        editdata.customerSex = data.data.customerSex;
        editdata.customerTelphone = data.data.customerTelphone;
        editdata.defaultCarLicense = data.data.defaultCarLicense;
        editdata.customerCompany = data.data.customerCompany;
        editdata.customerDepartment = data.data.customerDepartment;
        editdata.customerAddress = data.data.customerAddress;
        editdata.customerRoomNumber = data.data.customerRoomNumber;
        editdata.identityCardNumber = data.data.identityCardNumber;
        editdata.identityCardImg = data.data.identityCardImg;
        editdata.remark1 = data.data.remark1;
        editdata.remark2 = data.data.remark2;
        editdata.remark3 = data.data.remark3;
        editdata.identityCardImgPic = '';
        editdata.carConfigList1 = data.data.carConfigList;
        //end
        console.log("+++++++");
        console.log(editdata.carConfigList1);
        
        _this.carCodeListStr=[];
        _this.carCodeListArr=[];
        for (var i = 0; i < editdata.carConfigList1.length; i++) {
          console.log(editdata.carConfigList1[i].id);
        _this.carModalData.id = editdata.carConfigList1[i].id;
        _this.carModalData.parkCustomerId = editdata.carConfigList1[i].parkCustomerId;
        _this.carModalData.carLicenseNumber = editdata.carConfigList1[i].carLicenseNumber;
        _this.carModalData.carOwnType = editdata.carConfigList1[i].carOwnType;
        _this.carModalData.carCardNumber = editdata.carConfigList1[i].carCardNumber;
        _this.carModalData.carLogo = editdata.carConfigList1[i].carLogo;
        _this.carModalData.carColor = editdata.carConfigList1[i].carColor;
        _this.carModalData.carModel = editdata.carConfigList1[i].carModel;
        _this.carModalData.carSizeType = editdata.carConfigList1[i].carSizeType;
        _this.carModalData.drivingLicensePicture = editdata.carConfigList1[i].drivingLicensePicture;
        _this.carModalData.drivingLicensePic = '';
        _this.AddcarCodeList();
      }
        
      }, err => { });
      this.traderModal_open(editdata)
    },
    traderModal_open(editdata) {
      var _this = this;
      _this.traderpic = '';
      _this.carpic = '';
      _this.traderstatus = "new";
      _this.carCodeListStr = [];
      _this.carCodeListArr = [];
      _this.traderModalData = {
          url: "/parkVip/parkCustomer/save.do",
          id: null,
          customerName: "",
          customerSex: '',
          customerTelphone: "",
          defaultCarLicense: "",
          customerCompany: "",
          customerDepartment: "",
          customerAddress: "",
          customerRoomNumber: "",
          identityCardNumber: "",
          identityCardImg: "",
          remark1: "",
          remark2: "",
          remark3: "",
          identityCardImgPic: "",
          carConfigList1: {},
      };
      _this.tempPic={
          drivingLicensePicture: "",
          drivingLicensePic: ""
      };
      if (editdata) {
        _this.traderModalData = editdata;
        _this.traderstatus = "edit";
      }
      _this.toOpenModal('userModal')
    },

    carModal_open(editdata) {
      var _this = this;
      _this.drivingLicensePic = '';
      _this.carstatus = "new",
      _this.carModalData = {
          url: "",
          id: null,
          carLicenseNumber: "",
          carCardNumber: '',
          carOwnType: "",
          carLogo: "",
          carColor: "",
          carModel: "",
          carSizeType: "",
          drivingLicensePicture: "",
          drivingLicensePic: "",
      };
      _this.tempPic={
        drivingLicensePicture: "",
        drivingLicensePic: ""
      };
      if (editdata) {
        _this.carModalData = editdata;
        _this.carstatus = "edit";
      }
      _this.toOpenModal('carModal')
    },

    traderModal_save() {
      var _this = this;
      this.traderModalData.defaultCarLicense = _this.carCodeListStr[0];
      _this.$refs['user_form'].validate((valid) => {
        if (valid) {
          //this.traderModalData.defaultCarLicense = _this.carCodeListStr[0];
          var params = _this.traderModalData;
          var url = "/parkVip/parkCustomer/save.do";
          params.telIsEdit = true;
          params.carConfigList1=JSON.stringify(_this.carCodeListArr);

          // if (_this.traderpic) {
          //   params.identityCardImgPic = _this.traderpic;
          // }
          api.fetchPost(url, params).then(response => {
            console.log('userModal_save ==== response', response);
            if (response.status == 1) {
              // icon: 0:普通提示 1：正确的提示 2： 错误提示
              // time: 不填默认1000ms
              _this.showToast(response.message, 1, 2000);
              _this.resetForm('user_form');
              _this.closed('userModal');
              _this.getList();
            } else {
              _this.showToast(res.message, 2, 2000)
              return;
            }
          }, err => {
            console.log(err);
          })
        }
      });
    },

    AddcarCodeList() {
      let carOwnType = '';      
      let carModalObj = this.carModalData;
      switch (this.carModalData.carOwnType) {
        case 'PRIVATE_CAR':
          carOwnType = "私"
          break;
        case 'PUBLIC_CAR':
          carOwnType = "公"
          break;
        case 'UNKNOWN':
          carOwnType = "未知"
          break;
        default:
          break;
      }
      let str = carModalObj.carLicenseNumber + "(" + carModalObj.carCardNumber + ")" + "(" + carOwnType + ")"
      this.carCodeListStr.push(str);
      this.carCodeListArr.push(JSON.parse(JSON.stringify(carModalObj)));
    },

    EditcarCodeList(index) {
      var _this=this;
      _this.carCodeListStr.splice(index,1);
      _this.carCodeListArr.splice(index,1);
      let carOwnType = '';
      if (_this.carpic) {
        _this.carModalData.drivingLicensePic = _this.tempPic.drivingLicensePic;
        _this.carModalData.drivingLicensePicture = _this.tempPic.drivingLicensePicture;
      }
      let carModalObj = _this.carModalData;
      switch (_this.carModalData.carOwnType) {
        case 'PRIVATE_CAR':
          carOwnType = "私"
          break;
        case 'PUBLIC_CAR':
          carOwnType = "公"
          break;
        case 'UNKNOWN':
          carOwnType = "未知"
          break;
        default:
          break;
      }
      let str = carModalObj.carLicenseNumber + "(" + carModalObj.carCardNumber + ")" + "(" + carOwnType + ")"
      
      _this.carCodeListStr.push(str);
      _this.carCodeListArr.push(JSON.parse(JSON.stringify(carModalObj)));
    
    },

    carCode_edit(index) {
      var _this = this;
      _this.carModalData = _this.carCodeListArr[index];
      _this.editNum = index;
      _this.carstatus= "edit"
      _this.toOpenModal('carModal')
    },
    carCode_del(index) {
      this.carCodeListArr.splice(index, 1);
      this.carCodeListStr.splice(index, 1);
    },
    carModal_save() {
      var _this = this;
      _this.$refs['car_form'].validate((valid) => {
        if(valid){
          if(_this.carstatus== "new"){
            _this.AddcarCodeList();
          }else{
            _this.EditcarCodeList(_this.editNum);
          }
          _this.closed('carModal');
          return;

        }
      })
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getTraderList(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.park.GetParkCustomerData(params)
        .then(res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        }, err => { })
    },
    exportData() {
      let self = this;
      let params = {
      };
      params = $.extend({}, params, this.searchParams);
      self.showDialog("是否确认导出?", '', function () {
        self.toExport('parkVip/parkCustomer/exportParkCustomer.do', params)
      })
    },

    // 导入
    importData() {
      var self = this;
      self.startImportResultTimer(self);
      self.toOpenModal('importModal');
    },
    startImportResultTimer(self) {
      function intervalFunc() {
        $.ajax({
          url: '/mgr/parkVip/parkCustomer/getImportCustomerResult.do',
          dataType: "json",
          data: {},
          type: 'get',
          success: function (result) {
            if (result.status == 1) {
              self.importResult = result.data;
              console.log(!self.importResult || (self.importResult.totalCount == self.importResult.processedCount));
              if (!self.importResult || (self.importResult.totalCount == self.importResult.processedCount)) {
                clearInterval(getImportResultTimer);
              }
            }
          }
        });//ajax end
      }
      intervalFunc();
      var getImportResultTimer = setInterval(function () {
        intervalFunc();
      }, 1000);//interval end
    },
    getFile(event) {
      this.importFile.importFile = event.target.files[0];
    },
    sureImport(event) {
      var self = this;
      event.preventDefault();
      var formData = new FormData();
      formData.append("importFile", self.importFile.importFile);
      formData.append("im12portFile", 'self.importFile.importFile');
      formData.append("filename", self.importFile.importFile.name.replace('.xls', ''));
      if (!self.importFile.importFile) {
        self.showToast('请先选择文件', 1)
        return false;
      }
      
      var objtype = self.importFile.importFile.name.substring(self.importFile.importFile.name.lastIndexOf(".")).toLowerCase();
      if (objtype != '.xls') {
        self.showToast('只支持xls格式文件', 1)
        return false;
      }
      this.billImportBills(formData).then(res => {
        //start
        var data = res;
        if (res.status == 1) {
          //self.importResult = res.data;
          self.importFile.importFile = '';
          $("#fileInput").val('');
          setTimeout(function () {
              self.startImportResultTimer(self);
          }, 1000);
          self.getList();
        }
        //end
      }, err => { });
    },
    billImportBills(formData) {
      return api.fetchPostFile('/parkVip/parkCustomer/importParkCustomer.do', formData);
    },
    // 下载模板
    downloadTmp() {
      var self = this;
      let params = {
        "fileName": "park_customer_import",
        "fileType": "xls"
      }
      // this.toExport('importFlie/createExcelTmp.do', params);
      $.ajax({
        url: '/mgr/importFlie/createExcelTmp.do',
        dataType: "json",
        data: params,
        type: 'get',
        success: function (result) {
          var r = result;
          if (r.success) {
            if (r && r.success) {
              self.showToast('下载成功', 1);
              window.location.href = encodeURI("/mgr/common/templateDownload.do?fileName=" + r.fileName);
            } else {
              self.showToast('下载失败', 2);
            }
          }
        }
      });//ajax end
    },
    downloadError() {
      var self = this;
      if (self.importResult.errorFileName != "") {
        window.location.href = encodeURI("/mgr/common/downloadNotDelete.do?fileName=" + self.importResult.errorFileName);
      }
    },
    deleteTrader(trader) {
      var self = this;
      var params = {
        parkCustomerId: trader.id,
      };
      self.showDialog("确认删除该用户?", '', function () {
        API.park.parkCustomerDel(params).then(res => {
          //start
          var data = res;
          self.showToast('删除成功', 1);
          self.getList();
          //end
        }, err => { });
      });
    }
  }
}